package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.POJO.Setmeal;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    //引入生成页面的目录的路径
    @Value("${out_put_path}")
    private String outputPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetMealAndCheckGroup(setmealId,checkgroupIds);

        //将图片名称保存到Redis集合
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }
    //生成静态页面:套餐列表,套餐详情
    public void generateMobileStaticHtml(){
        //生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.findAll();

        //生成套餐列表静态页面
        generateMobileSetMealListHtml(list);

        //套餐详情静态页面
        generateMobileSetMealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetMealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据,用于生成静态页面
        map.put("setmealList",list);
        this.generaHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面(可能有多个,需要遍历)
    public void generateMobileSetMealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            //setmeal是套餐列表详情,并没有查询检查组,检查项详细信息,调用setmealDao的findByID方法可以查询出来
            map.put("setmeal",setMealDao.findById(setmeal.getId()));
            generaHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }


    }

    private void generaHtml(String templateName, String htmlPageName, Map dataMap) {
        Writer out = null;
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //通过配置对象获取模板对象
        try {
            Template template = configuration.getTemplate(templateName);

            /**
             * 通过模板产生一个静态文件,使用输出流指定文件位置
             * outputPath 磁盘路径
             * htmlPageName 文件名
             */
            out = new FileWriter(new File(outputPath + "/" + htmlPageName));
            //输出文件
            template.process(dataMap,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {

        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> setmeals =  setMealDao.selectByCondition(queryString);
        long total = setmeals.getTotal();
        List<Setmeal> rows = setmeals.getResult();
        PageResult pageResult = new PageResult(total,rows);
        return pageResult;
    }

    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

//    根据套餐ID查询套餐详情（套餐基本信息、套餐对应的检查组信息、检查组对应的检查项信息）
    public Setmeal findById(int id) {
        return setMealDao.findById(id);
    }


    //设置套餐和检查组多对多关系,操作t_setmeal_checkgroup中间表
    public void setSetMealAndCheckGroup(Integer setmealId,Integer[] checkgroupIds){
            if (checkgroupIds != null && checkgroupIds.length > 0){
                for (Integer checkGroupId : checkgroupIds) {
                    Map<String,Integer> map = new HashMap<>();
                    map.put("setmealId",setmealId);
                    map.put("checkGroupId",checkGroupId);
                    setMealDao.setSetMealAndCheckGroup(map);
                }
            }

    }
}
